using System;
using System.Collections.Generic;
namespace MicroMsg.Common.Timer
{
	public class TimerService
	{
		private static List<TimerObject> listTimerObject = new List<TimerObject>();
		private static object listLock = new object();
		public static TimerObject addTimer(int interval, EventHandler handler)
		{
			return TimerService.createTimerEx(interval, handler, interval, -1, null);
		}
		public static TimerObject addTimer(int interval, EventHandler handler, TimerEventArgs args)
		{
			return TimerService.createTimerEx(interval, handler, interval, -1, args);
		}
		public static TimerObject addTimer(int interval, EventHandler handler, int first, int repeat)
		{
			return TimerService.createTimerEx(interval, handler, first, repeat, null);
		}
		public static TimerObject addTimer(int interval, EventHandler handler, int first, int repeat, TimerEventArgs args)
		{
			return TimerService.createTimerEx(interval, handler, first, repeat, args);
		}
		public static void removeTimer(TimerObject timerObject)
		{
			if (timerObject == null)
			{
				return;
			}
			lock (TimerService.listLock)
			{
				TimerService.listTimerObject.Remove(timerObject);
			}
		}
		private static void addTimerEx(TimerObject timerObject)
		{
			lock (TimerService.listLock)
			{
				if (!TimerService.listTimerObject.Contains(timerObject))
				{
					TimerService.listTimerObject.Add(timerObject);
				}
			}
		}
		public static void runAllTimer()
		{
			lock (TimerService.listLock)
			{
				using (List<TimerObject>.Enumerator enumerator = TimerService.listTimerObject.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						TimerObject current = enumerator.get_Current();
						if (current != null)
						{
							current.method_0();
						}
					}
				}
			}
		}
		public static void cleanStopTimer()
		{
			TimerObject stopTimer = TimerService.getStopTimer();
			if (stopTimer != null)
			{
				TimerService.removeTimer(stopTimer);
			}
		}
		public static TimerObject getStopTimer()
		{
			lock (TimerService.listLock)
			{
				using (List<TimerObject>.Enumerator enumerator = TimerService.listTimerObject.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						TimerObject current = enumerator.get_Current();
						if (current != null && current.isStop())
						{
							return current;
						}
					}
				}
			}
			return null;
		}
		private static TimerObject createTimerEx(int interval, EventHandler evtHandler, int firstFire, int repeatCount, TimerEventArgs evtArgs)
		{
			TimerSource.checkSystemTimer();
			TimerParams timerParams = new TimerParams();
			timerParams.mEvtHandler = evtHandler;
			timerParams.mRepeatCount = repeatCount;
			timerParams.mEventArgs = evtArgs;
			timerParams.mInterval = interval;
			timerParams.mFirstFire = firstFire;
			TimerObject timerObject = new TimerObject();
			timerObject.init(timerParams);
			TimerService.addTimerEx(timerObject);
			return timerObject;
		}
	}
}
